<template>
    <div class="yxgl_wrap">
        <div class="page-content">
            <div class="header-box">

                <div class="btn-group">
                    <el-button class="hy_btn is_primary" type="primary" @click="handleAdd()">
                        <img src="../../assets/images/yxgl/icon_add.png" alt="">新增
                    </el-button>
                    <el-button class="hy_btn" @click="handleDel()">
                        <img src="../../assets/images/yxgl/icon_delete.png" alt="">删除
                    </el-button>
                    <el-button class="hy_btn" :disabled="multipleSelection.length>1" @click="handleEdit()">
                        <img src="../../assets/images/yxgl/icon_edit.png" alt="">修改
                    </el-button>
<!--                    <el-button class="hy_btn"><img src="../../assets/images/yxgl/icon_upload.png" alt="">上传Excel数据</el-button>-->
                    <!--  excel表格上传  -->
                    <el-upload
                            class="upload-demo"
                            drag
                            action="#"
                            multiple
                            accept=".xlsx,.xls"
                            :limit="1"
                            :http-request="uploadFile"
                    >
                        <el-button class="hy_btn"><img src="../../assets/images/yxgl/icon_upload.png" alt="">上传Excel数据</el-button>
                    </el-upload>
                </div>
            </div>

            <div class="table-box">
                <el-table
                        :data="tableData"
                        class="hy_table"
                        @selection-change="handleSelectionChange"
                >
                    <el-table-column
                            type="selection"
                            align="center"
                            width="60px">
                    </el-table-column>
                    <el-table-column
                            prop="yx_id"
                            label="编码">
                    </el-table-column>
                    <el-table-column
                            prop="yx_name"
                            label="名称">
                    </el-table-column>
                    <el-table-column
                            prop="datasetId"
                            label="数据组">
                    </el-table-column>
                    <el-table-column
                            prop="address"
                            label="地址编号">
                    </el-table-column>
                    <el-table-column
                            prop="alert"
                            align="center"
                            label="是否产生告警">
                        <template slot-scope="scope">
                            <i :class="scope.row.isLog ? 'el-icon-success' : 'el-icon-error' " :style="`color:${ scope.row.isLog ? '#35C759' : '#FF3B30' }; font-size: 18px;`"></i>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="warningLevel"
                            align="center"
                            label="告警等级">
                        <template slot-scope="scope">
                            <span>{{ scope.row.warningLevel === 'urgent' ? '紧急' : scope.row.warningLevel === 'important' ? '重要' : scope.row.warningLevel === 'secondary' ? '次要' : scope.row.warningLevel ?'提示' : '' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="relay"
                            align="center"
                            label="是否转发">
                        <template slot-scope="scope">
                            <i :class="scope.row.isTransfered ? 'el-icon-success' : 'el-icon-error' " :style="`color:${ scope.row.isTransfered ? '#35C759' : '#FF3B30' }; font-size: 18px;`"></i>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="relay"
                            align="center"
                            label="是否取反">
                        <template slot-scope="scope">
                            <i :class="scope.row.isInvert ? 'el-icon-success' : 'el-icon-error' " :style="`color:${ scope.row.isInvert ? '#35C759' : '#FF3B30' }; font-size: 18px;`"></i>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="addressMap"
                            align="center"
                            label="转发地址">
                    </el-table-column>
                </el-table>
            </div>

            <el-pagination
                    class="hy-pagination"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    background
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next"
                    :total="totalPage">
            </el-pagination>
        </div>

        <div style="height: 28px;"></div>

        <ControlDialog ref="controlDialog"
                       :dialogTitle="dialogTitle"
                       :fromList="fromList"
        ></ControlDialog>
    </div>
</template>

<script>
    import ControlDialog from '../ControlDialog';
    import XLSX from 'xlsx';

    export default {
        components: {
            ControlDialog,
        },
        data() {
            return {
                value: '',
                value1: [new Date(), new Date()],
                options: [],
                tableData: [],
                currentPage: 1,
                pageSize: 10,
                totalPage: 0,
                dialogTitle: '新增遥信',
                fromList: [
                    {
                        name: '编码',
                        type: 'input',
                        label: 'yx_id',
                        isRules: true,
                    },
                    {
                        name: '名称',
                        type: 'input',
                        label: 'yx_name',
                        isRules: true,
                    },
                    {
                        name: '数据组',
                        type: 'select',
                        label: 'datasetId',
                        isRules: true,
                        option: [],
                    },
                    {
                        name: '地址编号',
                        type: 'input',
                        label: 'address',
                    },
                    {
                        name: '是否产生告警',
                        type: 'select',
                        label: 'isLog',
                        isRules: true,
                        option: [
                            {value: true, label: '是'},
                            {value: false, label: '否'},
                        ],
                    },
                    {
                        name: '告警等级',
                        type: 'select',
                        label: 'warningLevel',
                        isRules: true,
                        option: [
                            {value: 'urgent', label: '紧急'},
                            {value: 'important', label: '重要'},
                            {value: 'secondary', label: '次要'},
                            {value: 'general', label: '提示'},
                        ],
                    },
                    {
                        name: '是否转发',
                        type: 'select',
                        label: 'isTransfered',
                        isRules: true,
                        option: [
                            {value: true, label: '是'},
                            {value: false, label: '否'},
                        ],
                    },
                    {
                        name: '是否取反',
                        type: 'select',
                        label: 'isInvert',
                        isRules: true,
                        option: [
                            {value: true, label: '是'},
                            {value: false, label: '否'},
                        ],
                    },
                    {
                        name: '转发地址',
                        type: 'input',
                        label: 'addressMap',
                    },
                ],
                multipleSelection: [],
            }
        },
        methods: {
            getData() {
                this.$api.queryYXList(
                    {
                        page: this.currentPage - 1,
                        pageSize: this.pageSize,
                    }
                ).then(( res )=> {
                    console.log("res==》",res)
                    this.totalPage = res.totalCount;
                    this.tableData = res.results || [];
                })
            },

            getChannelList () {
                this.$api.queryChannelList(
                    {
                        page: 0,
                        pageSize: 100,
                    }
                ).then(( res )=> {
                    var data = res.results || [];
                    var options = [];

                    for( var i=0; i<data.length; i++ ) {
                        options.push(
                            {value: data[i].c_id, label: data[i].c_name},
                        );
                    }

                    this.fromList[2].option = options;
                })
            },

            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.getData();
            },

            handleCurrentChange(val) {
                this.currentPage = val;
                this.getData();
            },

            handleAdd() {
                this.dialogTitle = '新增遥信';
                this.fromList[0].isDisabled = false;
                this.$refs.controlDialog.handleDisabled = false;
                this.$refs.controlDialog.dialogVisible = true;
            },

            handleEdit() {
                if( !this.multipleSelection.length ) {
                    this.$message.warning('请选择修改信息！')
                    return;
                }

                this.dialogTitle = '修改遥信';
                this.fromList[0].isDisabled = true;
                this.$refs.controlDialog.handleDisabled = false;
                this.$refs.controlDialog.handleForm =  this.multipleSelection[0];
                this.$refs.controlDialog.dialogVisible = true;
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            handleDel() {
                console.log("this.multipleSelection==>",this.multipleSelection)
                var arr = [];

                for( var i=0; i<this.multipleSelection.length; i++ ) {
                    arr.push(
                        {
                            yx_id: this.multipleSelection[i].yx_id,
                        }
                    )
                }

                this.$api.deleteYXList( arr ).then(( res )=> {
                    if( res.status !== 'success' ) {
                        return Promise.reject( res );
                    }
                    this.$message.success( '删除成功！' );
                    this.getData();
                }).catch(( err )=> {
                    this.$message.error( err.detail );
                })
            },

            handleSave( data ) {
                data.addressMap = data.addressMap ? data.addressMap*1 : '';
                data.address = data.address ? data.address*1 : '';

                if( this.dialogTitle === '修改遥信' ) {

                    this.$api.updateYXList( data ).then(( res )=> {
                        if( res.status !== 'success' ) {
                            return Promise.reject( res );
                        }
                        this.$message.success( '修改成功！' );
                        this.$refs.controlDialog.dialogVisible = false;
                        this.getData();
                    }).catch(( err )=> {
                        this.$message.error( err.detail );
                    })

                    return
                }

                this.$api.addYXList( data ).then(( res )=> {
                    if( res.status !== 'success' ) {
                        return Promise.reject( res );
                    }
                    this.$message.success( '新增成功！' );
                    this.$refs.controlDialog.dialogVisible = false;
                    this.getData();
                }).catch(( err )=> {
                    this.$message.error( err.detail );
                })
            },

            /**
             * 上传文件
             */
            uploadFile(params) {
                const _file = params.file;
                const fileReader = new FileReader();
                fileReader.onload = (ev) => {
                    try {
                        const data = ev.target.result;
                        const workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        for (let sheet in workbook.Sheets) {
                            //循环读取每个文件
                            const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
                            //若当前sheet没有数据，则continue
                            if(sheetArray.length == 0){
                                continue;
                            }
                            console.log("读取文件");
                            console.log(sheetArray);
                            var listTable = [];

                            for(let item in sheetArray){
                                let rowTable = {};


                                for( let i=0; i<this.fromList.length; i++ ) {
                                    if( this.fromList[i].type === 'select' ) {
                                        for( let j=0; j<this.fromList[i].option.length; j++ ) {
                                            if( sheetArray[item][ this.fromList[i].name ] === this.fromList[i].option[j].label ) {
                                                rowTable[ this.fromList[i].label ] = this.fromList[i].option[j].value;
                                                break;
                                            }
                                        }
                                    }else {
                                        rowTable[ this.fromList[i].label ] = sheetArray[item][ this.fromList[i].name ];

                                        if( this.fromList[i].label === 'yx_id'  ) {
                                            rowTable[ this.fromList[i].label ] += '';
                                        }

                                        if( this.fromList[i].label === 'yx_name'  ) {
                                            rowTable[ this.fromList[i].label ] += '';
                                        }
                                    }

                                }

                                listTable.push(rowTable)
                            }

                            this.batchInsert( listTable );


                        }
                    } catch (e) {
                        this.$message.warning('文件类型不正确！');
                    }
                };
                fileReader.readAsBinaryString(_file);
            },

            batchInsert( data ) {
                this.$api.batchInsertYXList( data ).then(( res )=> {
                    if( res.status !== 'success' ) {
                        return Promise.reject( res );
                    }
                    this.$message.success( '批量新增成功！' );
                    this.getData();
                }).catch(( err )=> {
                    this.$message.error( err.detail );
                })
            },

        },
        mounted() {
            this.getChannelList();
            this.getData();
        }
    }
</script>

<style lang="less">
    .yxgl_wrap {
        width: 100%;
        height: 100%;
        position: relative;

        >.page-content {
            width: 100%;
            min-height: 340px;
            padding: 40px;
            box-sizing: border-box;
            background: #FFFFFF;
            border-radius: 8px;

            >.header-box {
                width: 100%;
                height: 40px;
                margin-bottom: 32px;
                line-height: 40px;
                position: relative;

                >.btn-group {
                    position: absolute;
                    right: 0px;
                    top: 0px;

                    .el-button {

                        img {
                            position: relative;
                            top: -0.4px;
                        }
                    }

                    .el-button.hy_btn + .el-button.hy_btn {
                        margin-left: 16px;
                    }
                }
            }

            >.table-box {
                width: 100%;
            }
        }
    }
</style>
